﻿using System;
using System.Runtime.Serialization;
using System.Windows.Markup;
using nRoute.Controllers;
using nRoute.Internal;
using nRoute.Navigation;
using nRoute.Components;

namespace nRoute.SiteMaps
{
    [DataContract(Name= "ControllerActionNode")]
    [ContentProperty("ChildNodes")]
    public class ControllerActionNode
		 : SiteMapNode
    {
        private string _url;
        private ParametersCollection _urlParameters;
        private string _handlerName;

#region Properties

        [DataMember(IsRequired = true)]
        public string Url
        {
            get { return _url; }
            set
            {
                if (!string.Equals(_url, value, StringComparison.InvariantCulture))
                {
                    _url = value;
                    NotifyPropertyChanged(() => Url);
                }
            }
        }

        [DataMember(EmitDefaultValue = false)]
        public ParametersCollection UrlParameters
        {
            get
            {
                if (_urlParameters == null)
                {
                    _urlParameters = new ParametersCollection();
                    NotifyPropertyChanged(() => UrlParameters);
                }
                return _urlParameters;
            }
            set
            {
                if (_urlParameters != null)
                {
                    _urlParameters = value;
                    NotifyPropertyChanged(() => UrlParameters);
                }
            }
        }

        [DataMember(EmitDefaultValue = false)]
        public string HandlerName
        {
            get { return _handlerName; }
            set
            {
                if (!string.Equals(_handlerName, value, StringComparison.InvariantCulture))
                {
                    _handlerName = value;
                    NotifyPropertyChanged(() => IconPath);
                }
            }
        }

#endregion

#region Overrides

        public override void Execute()
        {
            Guard.ArgumentNotNullOrWhiteSpace(Url, "Url");

            if (!this.IsEnabled) return;
            ControllerService.Execute(
                new ControllerActionRequest(this.Url, this.UrlParameters, this.SiteArea, string.IsNullOrEmpty(HandlerName) ? 
                NavigationService.DefaultNavigationHandler : NavigationService.GetNavigationHandler(HandlerName)));
        }

#endregion

    }
}
